<gm:page title="Login Counter" authenticate="false" onload="init()">
  
  <gm:list id="datalist" data="${app}/counter" pagesize="1" template="dummytemplate">
    <gm:handleEvent event="repaint" execute="updateCounter()"/>
  </gm:list>
  
  <gm:template id="dummytemplate">
    <p style="display:none" repeat="true"/>
  </gm:template>
  
  <h3 id="message"/>
  
  <p style="display:none"><a href="#" id="signinlink">Sign in</a> to get counted.</p>
  <p id="thanks" style="display:none">Thanks for signing in! You have been counted.</p>
  
  <script type="text/javascript">
    function PersistentObject(feed, name, defaultValue) {
      this.feed=feed;
      this.path=new GPath("gmd:"+name);
      if(this.feed.size()==0){
        if(this.feed.canCreate()){
          this.entry=this.feed.createEntry();
          this.path.setValue(this.entry,defaultValue);
          this.feed.addEntry(this.entry);
        }
        else{
          this.entry=null;
        }
      }
      else{
        this.entry=this.feed.entryAt(0);
        if(this.path.getValue(this.entry)==null){
          this.path.setValue(this.entry,defaultValue);
          this.feed.updateEntry(this.entry);
        }
      }
    }
    PersistentObject.prototype.getValue=function(){
      return this.entry!=null?this.path.getValue(this.entry):null;
    }
    PersistentObject.prototype.setValue=function(value){
      if(this.entry!=null){
        this.path.setValue(this.entry,value);
        this.feed.updateEntry(this.entry);
      }
    }
    
    function updateCounter(){
      if(counted)return;
      var feed=google.mashups.getObjectById("datalist").getData();
      var since=new PersistentObject(feed,"since",new Date().toLocaleString()).getValue();
      var counter=new PersistentObject(feed,"counter",0);
      var value=counter.getValue();
      if(value!=null){
        if(google.mashups.isUserAuthenticated()){
          value=String(parseInt(value)+1);
          counter.setValue(value);
        }
        document.getElementById("message").innerHTML=
          'People have signed in to this mashup '+value+' times since '+since+'.';
        counted=true;
      }else{
        alert("You must sign in first!");
      }
    }
    
    function init(){
      if(!google.mashups.isUserAuthenticated()){
        document.getElementById("signinlink").href=google.mashups.properties['loginURL'];
        document.getElementById("signinlink").parentNode.style.display='';
      }else{
        document.getElementById("thanks").style.display='';
      }
      counted=false;
    }
  </script>

</gm:page>